package com.itheima.reggie.controller;

import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.SmsTemplate;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.time.Duration;
import java.util.Map;

@RestController
public class UserController {

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private HttpSession session;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;


    //接收验证码并验证
    @PostMapping("/user/sendMsg")
    public ResultInfo sendMsg(@RequestBody Map<String,String> param){
        String phone = param.get("phone");
        //String code = RandomUtil.randomNumbers(6); //Todo 先写死验证码
        String code="123";
        //smsTemplate.sendSms(phone,code); //TODO 教学先不发送
        //TODO 测试用，先设置时间为10秒生效，实际按需求更改
        redisTemplate.opsForValue().set("Msg"+phone,code, Duration.ofSeconds(10));
        return ResultInfo.success(null);
    }

    //登录
    @PostMapping("/user/login")
    public ResultInfo login(@RequestBody Map<String,String> params){
        String phone = params.get("phone");
        String code = params.get("code");
        /*String codeFromSession = (String) session.getAttribute("Msg" + phone);
        if (!StrUtil.equals(codeFromSession,code)) {
            throw new CustomException("验证码不一致...");
        }*/
        ResultInfo resultInfo = userService.login(phone, code);
        if (resultInfo.getCode()==1) {
            User user = (User) resultInfo.getData();
            session.setAttribute(Constant.SESSION_USER,user);
            redisTemplate.delete("Msg"+phone);
        }
        return resultInfo;
    }
    //退出登录
    @PostMapping("/user/logout")
    public ResultInfo logout(){
        session.invalidate();
        return ResultInfo.success(null);
    }

}
